import { IFlatPhones, IPhoneColor, IPhones } from "../typings";

/**
 * @description 该自定义hook完成数据扁平化
 * @param {IPhones[]} phoneList
 * @returns {IFlatPhones[]} 扁平化后的数据
 * 
 * 将数据结构A => 数据结构B 
 * 
 * 数据结构A：
 * {
 *   color: [{…}, {…}, {…}, {…}],
 *   id: 1,
 *   limit: 3,
 *   name: "IPhone 12",
 *   version: [{…}, {…}, {…}]
 * }
 * 
 * 数据结构B：
 * {
 *   color: [{…}, {…}, {…}, {…}],
 *   id: 1,
 *   limit: 3,
 *   name: "IPhone 12",
 *   version: [{…}, {…}, {…}],
 *   currentColor: {
 *     cid: 1,
 *     img: "https://img10.360buy....jpg",
 *     mark: "black",
 *     title: "黑色"
 *   }
 * }
 */
function useFlatPhoneList(phoneList: IPhones[]): IFlatPhones[] {
  let flatPhoneList: IFlatPhones[] = [];

  //遍历每一项phone
  phoneList.map((phone: IPhones) => {
    //遍历每一项phone.color
    //将color字段内容进行扁平化
    phone.color.map((c: IPhoneColor) => {
      let _phone: IFlatPhones = {
        //平铺原来的phone
        ...phone,
        //新增currentColor字段 
        currentColor: c
      }

      //将拼接好字段的对象放入新定义的flatPhoneList数组
      flatPhoneList.push(_phone);

      return c;
    });

    return phone;
  });

  return flatPhoneList;
}

export default useFlatPhoneList;